import React, { useState, useRef, useEffect } from "react";
import { Button, Drawer, Space, Tabs } from "antd";
import PubSub from "pubsub-js";
import store from "../../redux/store";
import axios from "axios";
import MiniChart from "../MiniChart";
const DrawerComp = () => {
  const [open, setOpen] = useState(false);
  const placement = "right";
  useEffect(() => {
    const subscription = PubSub.subscribe("open", (msg, data) => {
      setOpen(data);
    });
    return () => {
      PubSub.unsubscribe(subscription);
    };
  }, []);
  const onClose = () => {
    setOpen(false);
  };
  return (
    <>
      <Drawer
        title="相对节点具体依赖"
        placement={placement}
        width={600}
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button type="primary" onClick={onClose}>
              返回
            </Button>
          </Space>
        }
      >
        <List />
      </Drawer>
    </>
  );
};
//Drawer中的导航栏
const initialItems = [
  {
    label: "具体依赖",
    children: "暂时还没有数据...",
    key: "1",
    closable: false,
    falg: 0,
  },
];

const List = () => {
  //获取从item中点击事件之后传入store的数据
  const searchRef = useRef("");
  const itemRef = useRef("");
  const data = store.getState();
  const [nodes, setNodes] = useState([]);
  const [links, setLinks] = useState([]);
  useEffect(() => {
    console.log(data, "drawer中的data");
    let dataIn = {
      filename: data.item,
      depth: 2,
    };
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "http://localhost:3000/getDependencies",
          { params: dataIn }
        );
        console.log(response.data);
        const linkstempArr = response.data.links;
        const nodestemp = response.data.nodes;
        const nodestempArr = nodestemp.map((item, index) => {
          return {
            id: item.name,
            label: item.name,
            version: item.version,
          };
        });
        setNodes(nodestempArr);
        setLinks(linkstempArr);
      } catch (error) {
        console.error(error);
      }
    };
    fetchData();

    return () => {};
  }, [data.item]);
  useEffect(() => {
    let dataIn2 = {
      filename: data.seach,
      depth: 2,
    };
    const fetchData2 = async () => {
      try {
        const response = await axios.get(
          "http://localhost:3000/getDependencies",
          { params: dataIn2 }
        );
        const linkstempArr = response.data.links;
        const nodestemp = response.data.nodes;
        const nodestempArr = nodestemp.map((item, index) => {
          return {
            id: item.name,
            label: item.name,
            version: item.version,
          };
        });
        setNodes(nodestempArr);
        setLinks(linkstempArr);
      } catch (error) {
        console.error(error);
      }
    };
    fetchData2();
  }, [data.seach]);
  useEffect(() => {
    console.log(nodes, links, "在Drawer中get请求获取的数据");
    console.log(searchRef.current, itemRef.current);
    const { seach, item } = data;
    if (item !== null || seach !== null) {
      // eslint-disable-next-line no-labels
      outer: {
        if (searchRef.current !== seach) {
          console.log("进入设置导航栏内容的nodes数据", nodes);
          add(<MiniChart nodes={nodes} links={links} />, seach, 0);
          searchRef.current = seach;
          // eslint-disable-next-line no-labels
          break outer;
        }
        if (itemRef.current !== item) {
          console.log("进入设置导航栏内容的nodes数据", nodes);
          add(<MiniChart nodes={nodes} links={links} />, item, 1);
          itemRef.current = item;
        }
      }
    }
  }, [nodes, links]);
  //初始值为：initialItems[0].key=1
  const [activeKey, setActiveKey] = useState(initialItems[0].key);
  const [items, setItems] = useState(initialItems);
  const newTabIndex = useRef(0);
  const onChange = (newActiveKey) => {
    setActiveKey(newActiveKey);
  };
  const add = (
    children = "Content of new Tab",
    label = "New Tab",
    flag = 0
  ) => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    console.log(newActiveKey);
    const newPanes = [...items];
    newPanes.push({
      label: label,
      children: children,
      key: newActiveKey,
      flag: flag,
    });
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };
  const remove = (targetKey) => {
    items.map((temp) => {
      if (temp.key === targetKey) {
        if (temp.flag === 0) {
          data.seach = null;
          searchRef.current = null;
          console.log("改变searchRef的值", searchRef.current);
        }
        if (temp.flag === 1) {
          data.item = null;
          itemRef.current = null;
          console.log("改变itemRef的值", itemRef.current);
        }
      }
      return temp;
    });
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };
  const onEdit = (targetKey, action) => {
    remove(targetKey);
  };
  return (
    <Tabs
      type="editable-card"
      onChange={onChange}
      activeKey={activeKey}
      onEdit={onEdit}
      items={items}
      nodes={nodes}
      links={links}
    ></Tabs>
  );
};
export default DrawerComp;
